package com.example.service.Imp;

import com.example.common.b_pojo.BAdmin;
import com.example.common.b_pojo.BAdminRole;
import com.example.common.b_pojo.BAdminUser;
import com.example.common.b_pojo.BRole;
import com.example.common.utils.ResultCodeEnum;
import com.example.dao.mapper.BAdminMapper;
import com.example.dao.mapper.BAdminRoleMapper;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImp implements UserService {

    private final PasswordEncoder passwordEncoder;

    @Autowired
    private BAdminMapper bAdminMapper;

    @Autowired
    private BAdminRoleMapper bAdminRoleMapper;

    @Autowired
    public UserServiceImp(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Boolean registerAdmin(String admin, String password, String phone) {
        List<BAdmin> bAdmins = bAdminMapper.selectByAdminAndPhoneBAdmin(admin, phone);
        if (bAdmins.size() != 0){
            return false;
        }
        BAdmin bAdmin = new BAdmin();
        bAdmin.setAdmin(admin);
        bAdmin.setPassword(passwordEncoder.encode(password));
        bAdmin.setPhone(phone);
        int insert = bAdminMapper.insert(bAdmin);
//        代码中获取mybatisplus的主键，插入成功后，主键会自动回填到bAdmin对象中
        bAdminRoleMapper.insert(new BAdminRole(bAdmin.getId(),2L));
        if (insert == 1){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<BRole> AdminInfo(Long id) {
        List<BRole> roles=bAdminMapper.selectRoleAndMenuById(id);
        if (roles.size() == 0){
            throw new RuntimeException(String.valueOf(ResultCodeEnum.BUSINESS_ERROR));
        }
        return roles;
    }

}
